﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using WebApp.Models;
using WebApp.Services;

namespace WebApp.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IPowerHostService _powerservice;
        private readonly IPowerDataService _appService;

        private bool Verify()
        {
            var appId = Convert.ToInt32(Request.Query["appid"].ToString());
            var app = _appService.GetApplication(appId);
            if (app == null)
                return false;
            var signature = Request.Query["signature"].ToString();
            var timestamp = Request.Query["timestamp"].ToString();
            var nonce = Request.Query["nonce"].ToString();
            var param = new string[] { app.AppToken, timestamp, nonce }.OrderBy(p => p);
            var input = string.Join("", param);
            //Console.WriteLine($"GetSha1Hash={Helper.GetSha1Hash(input)}");
            return Utility.VerifySha1Hash(input, signature);
        }
        public HomeController(IPowerDataService appService, ILogger<HomeController> logger, IPowerHostService powerservice)
        {
            _logger = logger;
            _powerservice = powerservice;
            _appService = appService;
        }

        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> StopAsync()
        {
            var app = _appService.GetApplication(1);
            await _powerservice.DeviceCommandAsync(new IoTCmdReq { AppId = 1, MeterCode = "300219100223", Command = "9010", CallbackUrl = "", RequestId = "" });
            return Json(new { Success = true });
        }
        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
